<?php

namespace app\api\service\weixin;

use think\Db;
use think\Exception;
use app\admin\model\Rechargerecord;
use app\admin\model\Member;

use think\Loader;
use think\Log;
use think\Cache;

Loader::import('WxPay.WxPay', EXTEND_PATH, '.Api.php');

/**
 * 处理微信支付回调
 * Class WxNotify
 * @package app\api\service
 */
class RechargeNotify extends \WxPayNotify
{

    //<xml>
    //<appid><![CDATA[wx2421b1c4370ec43b]]></appid>
    //<attach><![CDATA[支付测试]]></attach>
    //<bank_type><![CDATA[CFT]]></bank_type>
    //<fee_type><![CDATA[CNY]]></fee_type>
    //<is_subscribe><![CDATA[Y]]></is_subscribe>
    //<mch_id><![CDATA[10000100]]></mch_id>
    //<nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
    //<openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
    //<out_trade_no><![CDATA[1409811653]]></out_trade_no>
    //<result_code><![CDATA[SUCCESS]]></result_code>
    //<return_code><![CDATA[SUCCESS]]></return_code>
    //<sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>
    //<sub_mch_id><![CDATA[10000100]]></sub_mch_id>
    //<time_end><![CDATA[20140903131540]]></time_end>
    //<total_fee>1</total_fee>
    //<trade_type><![CDATA[JSAPI]]></trade_type>
    //<transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
    //</xml>
    public function NotifyProcess($data, &$msg)
    {
        if ($data['result_code'] == 'SUCCESS') {
            Db::startTrans();
            try {
                $orderNo = $data['out_trade_no'];
                $Rechargerecord = new Rechargerecord();

                $order = $Rechargerecord->where('order_no', $orderNo)->find();
                if (!$order) {
                    Db::rollback();
                    Log::record('订单不存在');
                    return false;
                }

                // 更新用户余额
                $total_fee = $order['record_money'] + $order['gift_money'];
                $memberMdl = new Member();

                $memberUpdate = $memberMdl->where('id', $order['member_id'])->setInc('balance', $total_fee);
                if ($memberUpdate === false) {
                    return false;
                }

                // 更新订单状态
                $result = $Rechargerecord->where('order_no', $orderNo)->update(['status' => 1]);
                if($result === false){
                    Log::record('更新订单状态失败');
                    return false;
                }

                Db::commit();
                return true;
            } catch (Exception $ex) {
                Db::rollback();
                Log::record($ex->getMessage(), 'error');
                return false;
            }
        } else {
            return true;
        }
    }
}